package fr.ul.ade.secunde.sync;

import java.util.Calendar;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import fr.ul.ade.secunde.database.AdeWebContract;
import fr.ul.ade.secunde.util.AdeWebFactory;

/**
 * Classe responsable de la synchronisation d'un emploi du temps.
 * 
 * @author Michaël Schnell
 * @since Jul 28, 2013
 * 
 * @version 1.3
 */
public class ScheduleUpdateRunnable
		implements Runnable {

	/**
	 * Identifiant de l'emploi du temps synchronisation.
	 */
	private long scheduleId;

	/**
	 * Référence vers la connextion à ADE utilisée pour cette synchronisation.
	 */
	private AdeWebInterface connection;

	private Context context;

	public ScheduleUpdateRunnable(long scheduleId, AdeWebInterface connection,
			Context context) {
		this.scheduleId = scheduleId;
		this.connection = connection;
		this.context = context;
	}

	@Override
	public void run() {
		try {
			final Cursor schedule = this.context.getContentResolver()
					.query(AdeWebContract.Schedule.buildUri(this.scheduleId),
							ScheduleQuery.PROJECTION,
							null,
							null,
							AdeWebContract.Schedule.DEFAULT_SORT);
			if (!schedule.moveToFirst()) {
				throw new Exception("Invalid schedule id: " + this.scheduleId);
			}

			final Calendar calendar = Calendar.getInstance();
			final Date now = calendar.getTime();
			calendar.add(Calendar.DAY_OF_YEAR,
					schedule.getInt(ScheduleQuery.SCHEDULE_PERIOD));
			final Date to = calendar.getTime();
			final Cursor newSchedule = this.connection.getEvents(now,
					to,
					schedule.getString(ScheduleQuery.SCHEDULE_ALL_RESOURCES));
			Log.d("[run]", "Fetched events: " + newSchedule.getCount());
			// FIXME à supprimer
			this.connection.disconnect();

			ScheduleComparator comparator = AdeWebFactory
					.buildComparator(this.scheduleId, this.context);
			comparator.prepare();
			Log.d("[run]", "Comparing schedules ...");
			comparator.compare(newSchedule);
			Log.d("[run]", "Committing changes ....");
			comparator.commitChanges();
			comparator.commitDisplay();
			Log.d("[run]", "Finished updating ....!");

			newSchedule.close();
			schedule.close();
		} catch (Exception e) {
			Log.e("[updateSchedule]", "Update failed !", e);
		}
		// catch (IOException ioe) {
		// // FIXME Log and report exception !
		// } catch (NotFoundException nfe) {
		// // TODO: handle exception
		// } catch (XmlPullParserException xppe) {
		// // FIXME Log and report exception !
		// }
	}

	// --------------------------------------------------------
	//
	// Données chargées
	//
	// --------------------------------------------------------

	protected interface ScheduleQuery {
		final String[] PROJECTION = { BaseColumns._ID,
				AdeWebContract.Schedule.SCHEDULE_ALL_RESOURCES,
				AdeWebContract.Schedule.SCHEDULE_PERIOD };

		final int _ID = 0;
		final int SCHEDULE_ALL_RESOURCES = 1;
		final int SCHEDULE_PERIOD = 2;
	}

}// class ScheduleUpdateRunnable